import { promisify } from './promisify';
import i18n from '@/i18n';

/**
 * 获取授权情况promisify封装
 * @param {String} keyName
 * @return {Promise}
 */
export const getSetting = keyName => {
  // #ifdef H5
  return Promise.resolve(true);
  // #endif
  // #ifndef H5
  return promisify(uni.getSetting)().then(
    ({ authSetting }) => authSetting[keyName]
  );
  // #endif
};

/**
 * 获取重新授权过程
 * @param {Object} dataJson
 * @return {Promise}
 */
export const reauthenticate = (
  keyName = '',
  { askMessage = '检测到未授权，是否重新授权' } = {}
) => {
  return new Promise((res, rej) => {
    getSetting(keyName).then(settingRs => {
      if (!settingRs) {
        showModal({
          title: '提示',
          content: askMessage,
          success: modalRs => {
            // 用户同意重新授权，跳转授权页面
            if (modalRs.confirm) {
              uni.openSetting({
                success: reSettingRs => {
                  // 用户成功重新授权，则重新获取授权信息并继续第一个授权时的resolve操作
                  if (reSettingRs.authSetting[keyName]) {
                    res();
                  } else {
                    // 这里是用户同意重新授权，但没点击授权
                    rej();
                  }
                }
              });
            } else {
              // 这里是用户不同意重新授权
              rej();
            }
          }
        });
      } else {
        res();
      }
    });
  });
};

/**
 * 小程序成功提示
 * @param {String} title
 * @param {Number} duration
 * @return {Promise}
 */
export const success = (title = '成功', duration = 2000) => {
  hideLoading();
  uni.showToast({
    title: i18n.getLocaleByName(title),
    duration,
    icon: 'success',
    mask: true
  });
  return wait(duration);
};

/**
 * 小程序失败提示
 * 2018-02-06 已取消图标，有图标的toast只能显示7个字 By Ben
 * @param {String} title
 * @param {Number} duration
 * @return {Promise}
 */
export const fail = (title = '失败', duration = 2000) => {
  hideLoading();
  uni.showToast({
    title: i18n.getLocaleByName(title),
    duration,
    icon: 'none',
    mask: true
  });
  return wait(duration);
};

/**
 * 小程序加载提示，传入时间则自动消失，不传入则需要手动取消
 * @param {String} title
 * @param {Number} duration
 * @return {Promise}
 */
export const loading = (title = '加载中..', duration) => {
  if (duration && typeof duration == 'number') {
    uni.showToast({
      title: i18n.getLocaleByName(title),
      duration,
      icon: 'loading',
      mask: true
    });
    return wait(duration);
  } else {
    return promisify(uni.showLoading)({
      title: i18n.getLocaleByName(title),
      mask: true
    });
  }
};

/**
 * 小程序提示 (没蒙层)
 * @param {String} title
 * @param {Number} duration
 * @return {Promise}
 */
export const toast = (title = '提示', duration = 2000) => {
  hideLoading();
  uni.showToast({
    title: i18n.getLocaleByName(title),
    duration,
    icon: 'none'
  });
  return wait(duration);
};

/**
 * 小程序取消加载框
 */
export const hideLoading = () => promisify(uni.hideLoading)();

/**
 * 小程序导航栏加载动画
 */
export const showNavigationBarLoading = () => uni.showNavigationBarLoading();

/**
 * 取消小程序导航栏加载动画
 */
export const hideNavigationBarLoading = () => uni.hideNavigationBarLoading();

/**
 * 小程序模态窗
 * 2018-12-17 这里不用promisify封装是因为封装了就无法用
 *            于用于点击后触发的openSetting权限 By Ben
 * 2019-07-11 回调真的太丑了，写了个判断，有传入回调就默认
 *            调用，没传就Promise化包装  By Ben
 * @param {Object} 参数
 */
export const showModal = ({
  title = '信息',
  content = '',
  showCancel = true,
  cancelText = '取消',
  cancelColor = '#000000',
  confirmText = '确定',
  confirmColor = '#a06c08',
  success,
  fail
} = {}) => {
  if (success || fail) {
    success = success || function() {};
    fail = fail || function() {};
    uni.showModal({
      title: i18n.getLocaleByName(title),
      content: i18n.getLocaleByName(content),
      showCancel,
      cancelText: i18n.getLocaleByName(cancelText),
      cancelColor,
      confirmText: i18n.getLocaleByName(confirmText),
      confirmColor,
      success,
      fail
    });
  } else {
    return new Promise((res, rej) => {
      uni.showModal({
        title: i18n.getLocaleByName(title),
        content: i18n.getLocaleByName(content),
        showCancel,
        cancelText: i18n.getLocaleByName(cancelText),
        cancelColor,
        confirmText: i18n.getLocaleByName(confirmText),
        confirmColor,
        success: ({ confirm }) => {
          if (confirm) {
            res();
          } else {
            rej('cancel have been click');
          }
        },
        fail: rej
      });
    });
  }
};

/**
 * 延迟时间 promisify封装
 * @param {Number} time
 * @return {Promise}
 */
export const wait = (time = 1000) => {
  return new Promise(res => {
    const timer = setTimeout(() => {
      clearTimeout(timer);
      res();
    }, time);
  });
};

/**
 * 获取是否微信内置浏览器
 */
export const isWxBroswer = () => {
  // #ifdef H5
  return navigator.userAgent.toLowerCase().includes('micromessenger');
  // #endif
  // #ifndef H5
  return false;
  // #endif
};

/**
 * 获取是否澳门通内置浏览器
 */
export const isMPayBroswer = () => {
  // #ifdef H5
  return navigator.userAgent.toLowerCase().includes('mpay');
  // #endif
  // #ifndef H5
  return false;
  // #endif
};

export const isAliPayBroswer = () => {
  // #ifdef H5
  return navigator.userAgent.toLocaleLowerCase().includes('alipay');
  // #endif
  // #ifndef H5
  return false;
  // #endif
};

export const isWxMiniProgram = () => {
  // #ifdef MP-WEIXIN
  return true;
  // #endif
  // #ifndef MP-WEIXIN
  return false;
  // #endif
};
